import { rankRecord } from '@/services/api/api-assess-week-emphasize-rank';
import { saveVoteProcess } from '@/services/api/api-assess-week-emphasize-vote';
import { CheckCircleTwoTone } from '@ant-design/icons';
import { ActionType, ModalForm, ProCard, ProColumns, ProTable } from '@ant-design/pro-components';
import { Badge, Button, Col, Descriptions, Divider, message, Radio, Row, Space, Table } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import React, { useEffect, useRef, useState } from 'react';
import DetailRecord from '../record/DetailRecord';
dayjs.extend(customParseFormat);

interface TableRankRecordProps {
  revote: number;
  range: AssessWeekEmphasizeVoteData.RangePage;
  onSave: () => void;
  onRefurbish: () => void;
}

const TableRankRecord: React.FC<TableRankRecordProps> = ({
  revote,
  range,
  onSave,
  onRefurbish,
}) => {
  const actionRef = useRef<ActionType>();

  const [dataReportType, setDataReportTypeState] = useState<React.Key>('1');
  const [datahubLevel, setDatahubLevelState] = useState<React.Key>('2000');

  const [voteSelectRecords, setVoteSelectRecordsState] = useState<any[]>([]);

  const [voteSelectRecordMap, setVoteSelectRecordsMapState] = useState<
    Map<string, any[] | undefined>
  >(new Map());

  const columns: ProColumns<AssessWeekEmphasizeRankData.RecordRank>[] = [
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          排名
        </span>
      ),
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
      align: 'center',
      render: (dom, entity, index, action) => {
        return (
          <Badge
            count={entity.topIndex}
            overflowCount={999}
            style={{
              padding: 0,
              // marginBlockStart: -2,
              // marginInlineStart: 4,
              fontSize: 12,
              color: '#FFF',
              backgroundColor: '#979797',
            }}
          />
        );
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          {datahubLevel == '2000' ? '媒体单位' : '区域'}
        </span>
      ),
      dataIndex: 'areaName',
      align: 'center',
      width: '150px',
      render: (dom, entity, index, action) => {
        if (datahubLevel == '2000') {
          return (
            <span
              style={{
                color: entity.isExhibition == 1 ? '#ffa500' : '',
              }}
            >
              {entity.appointSourceOrganizationNames.map((item) => item)}
            </span>
          );
        } else {
          return (
            <span
              style={{
                color: entity.isExhibition == 1 ? '#ffa500' : '',
              }}
            >
              {entity.areaName}
            </span>
          );
        }
      },
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          标题
        </span>
      ),
      dataIndex: 'dataName',
      align: 'center',
      ellipsis: true,
      copyable: true,
      width: '40%',
      render: (dom, entity, index, action) => (
        <div
          style={{
            textAlign: 'left',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
          }}
        >
          <DetailRecord
            entrance="vote"
            id={entity.id}
            name={entity.dataName}
            onRefurbish={function (): void {
              actionRef.current?.reloadAndRest();
            }}
            onExhibitionRefurbish={function (): void {
              actionRef.current?.reloadAndRest();
            }}
          />
        </div>
      ),
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          总分
        </span>
      ),
      dataIndex: 'totalScore',
      align: 'center',
      //sorter: true,
      width: '85px',
    },
    {
      title: (
        <span
          style={{
            color: '#99a3b7',
            fontSize: 12,
            textAlign: 'center',
            fontWeight: 'normal',
          }}
        >
          发布日期
        </span>
      ),
      dataIndex: 'dataReleaseTime',
      align: 'center',
      width: '100px',
      render: (dom, entity, index, action) => {
        return dayjs(entity.dataReleaseTime).format('YYYY-MM-DD');
      },
    },
  ];

  useEffect(() => {
    actionRef.current?.reloadAndRest();
  }, [range]);

  return (
    <>
      <ProCard
        ghost
        title={
          <span
            style={{
              fontSize: '16px',
              color: '#000000e0',
              fontWeight: '600',
            }}
          >{`${revote == 1 ? '重新投票' : '投票信息'}：${range.name}`}</span>
        }
        extra={
          <ModalForm
            key={'modal_form_release_state_discard'}
            autoFocusFirstInput
            title={
              <>
                <CheckCircleTwoTone
                  style={{
                    marginRight: 8,
                  }}
                  twoToneColor="#87d068"
                />
                {revote == 1 ? '重新投票：' : ''}确认提交
              </>
            }
            trigger={
              <Button
                type="primary"
                style={{
                  backgroundColor: '#87d068',
                }}
              >
                {revote == 1 ? '重新' : ''}提交投票
              </Button>
            }
            modalProps={{
              width: 400,
              destroyOnClose: true,
              onCancel: () => console.log('run'),
            }}
            submitTimeout={2000}
            submitter={{
              submitButtonProps: {
                type: 'primary',
                style: { background: '#87d068' },
              },
            }}
            onFinish={async (values) => {
              let records = new Array();

              voteSelectRecordMap.values()?.forEach((element: any) => {
                records = [...records, ...element];
              });

              const response = await saveVoteProcess({
                voteRangeId: range.id,
                recordIds: records.map((item) => item.id),
              });
              if (response.code === 0) {
                message.success('提交成功');
                setVoteSelectRecordsState([]);
                setVoteSelectRecordsMapState(new Map());
                onSave();
                return true;
              } else {
                return false;
              }
            }}
          />
        }
        bodyStyle={{
          paddingLeft: 8,
          paddingRight: 8,
        }}
      >
        <Row>
          <Col span={12}>
            <Descriptions
              size="small"
              column={1}
              title={
                <div>
                  <div
                    style={{
                      fontSize: '15px',
                    }}
                  >
                    市属媒体
                  </div>
                  <span
                    style={{
                      fontSize: '14px',
                      color: '#00000073',
                      fontWeight: 'normal',
                    }}
                  >
                    每项最多3条
                  </span>
                </div>
              }
            >
              <Descriptions.Item label="好报道">
                {voteSelectRecordMap.get(`1-2000`) ? (
                  voteSelectRecordMap.get(`1-2000`)?.length
                ) : (
                  <span
                    style={{
                      color: 'red',
                    }}
                  >
                    未选择
                  </span>
                )}
              </Descriptions.Item>
            </Descriptions>
            <Descriptions size="small" column={1}>
              <Descriptions.Item label="好评论">
                {voteSelectRecordMap.get(`2-2000`) ? (
                  voteSelectRecordMap.get(`2-2000`)?.length
                ) : (
                  <span
                    style={{
                      color: 'red',
                    }}
                  >
                    未选择
                  </span>
                )}
              </Descriptions.Item>
            </Descriptions>

            <Descriptions size="small" column={1}>
              <Descriptions.Item label="好创意报道">
                {voteSelectRecordMap.get(`3-2000`) ? (
                  voteSelectRecordMap.get(`3-2000`)?.length
                ) : (
                  <span
                    style={{
                      color: 'red',
                    }}
                  >
                    未选择
                  </span>
                )}
              </Descriptions.Item>
            </Descriptions>
          </Col>
          <Col span={12}>
            <Descriptions
              size="small"
              column={1}
              title={
                <div>
                  <div
                    style={{
                      fontSize: '15px',
                    }}
                  >
                    区县媒体
                  </div>
                  <span
                    style={{
                      fontSize: '14px',
                      color: '#00000073',
                      fontWeight: 'normal',
                    }}
                  >
                    每项最多8条
                  </span>
                </div>
              }
            >
              <Descriptions.Item label="好报道">
                {voteSelectRecordMap.get(`1-3000`) ? (
                  voteSelectRecordMap.get(`1-3000`)?.length
                ) : (
                  <span
                    style={{
                      color: 'red',
                    }}
                  >
                    未选择
                  </span>
                )}
              </Descriptions.Item>
            </Descriptions>

            <Descriptions size="small" column={1}>
              <Descriptions.Item label="好评论">
                {voteSelectRecordMap.get(`2-3000`) ? (
                  voteSelectRecordMap.get(`2-3000`)?.length
                ) : (
                  <span
                    style={{
                      color: 'red',
                    }}
                  >
                    未选择
                  </span>
                )}
              </Descriptions.Item>
            </Descriptions>

            <Descriptions size="small" column={1}>
              <Descriptions.Item label="好创意报道">
                {voteSelectRecordMap.get(`3-3000`) ? (
                  voteSelectRecordMap.get(`3-3000`)?.length
                ) : (
                  <span
                    style={{
                      color: 'red',
                    }}
                  >
                    未选择
                  </span>
                )}
              </Descriptions.Item>
            </Descriptions>
          </Col>
        </Row>
      </ProCard>
      <Divider />
      <Space align="end">
        <span
          style={{
            fontWeight: '600',
            fontSize: '16px',
            color: '#000000e0',
          }}
        >
          投票窗口
        </span>
        <span
          style={{
            fontSize: '14px',
            color: '#00000073',
            fontWeight: 'normal',
          }}
        >
          勾选后，可点击绿色按钮进行提交。
        </span>
      </Space>

      <ProTable<AssessWeekEmphasizeRankData.RecordRank>
        columns={columns}
        actionRef={actionRef}
        rowKey="id"
        request={async (params = {}, sorter) => {
          const response = await rankRecord({
            ...params,
            dataReleaseTimes: [range?.startDate, range?.endDate],
            dataReportTypes: [dataReportType],
            datahubLevelIds: [datahubLevel],
          });
          return {
            data: response.data,
            success: true,
            total: response.data?.length,
          };
        }}
        dateFormatter="id"
        defaultSize={'small'}
        pagination={false}
        search={false}
        options={{
          density: false,
          setting: false,
        }}
        ghost
        scroll={{
          x: '625px',
        }}
        rowSelection={{
          // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
          // 注释该行则默认不显示下拉选项
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          selectedRowKeys: [...voteSelectRecords.map((item) => item.id)],
          onSelect: (
            record: AssessWeekEmphasizeRankData.RecordRank,
            selected: boolean,
            selectedRows: AssessWeekEmphasizeRankData.RecordRank[],
            nativeEvent: Event,
          ) => {
            let selectRecords = new Array();

            if (selected) {
              //选中

              if (datahubLevel == '2000' && selectedRows.length > 3) {
                return message.warning('最多只能选择三个');
              } else if (datahubLevel == '3000' && selectedRows.length > 8) {
                return message.warning('最多只能选择八个');
              } else {
                // selectRecords = selectedRows.map((item) => item.id);
                selectRecords = selectedRows;
              }
            } else {
              //取消
              // selectRecords = selectedRows.map((item) => item.id);
              selectRecords = selectedRows;
            }

            voteSelectRecordMap.set(`${dataReportType}-${datahubLevel}`, selectRecords);
            setVoteSelectRecordsState(selectRecords);
            setVoteSelectRecordsMapState(voteSelectRecordMap);
          },
        }}
        tableAlertRender={false}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: dataReportType,
            items: [
              {
                key: '1',
                label: <span>好报道</span>,
              },
              {
                key: '2',
                label: <span>好评论</span>,
              },
              {
                key: '3',
                label: <span>好创意报道</span>,
              },
            ],
            onChange: (key) => {
              let records = voteSelectRecordMap.get(`${key}-${datahubLevel}`);
              if (records == undefined) {
                records = [];
              }
              setVoteSelectRecordsState(records);

              setDataReportTypeState(key as string);
              actionRef.current?.reloadAndRest();
            },
          },
          filter: (
            <Space>
              <Radio.Group
                defaultValue={'2000'}
                optionType="button"
                buttonStyle="solid"
                size="middle"
                onChange={(e) => {
                  let records = voteSelectRecordMap.get(`${dataReportType}-${e.target.value}`);
                  if (records == undefined) {
                    records = [];
                  }
                  setVoteSelectRecordsState(records);

                  setDatahubLevelState(e.target.value);
                  actionRef.current?.reloadAndRest();
                }}
              >
                <Radio.Button value="2000">市属媒体</Radio.Button>
                <Radio.Button value="3000">区县媒体</Radio.Button>
              </Radio.Group>
            </Space>
          ),
        }}
      />
    </>
  );
};
export default TableRankRecord;
